package com.vogue.supplymall.order.domain.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.vogue.ssm.database.entity.SnowflakeIdWorker;
import com.vogue.supplymall.common.domain.dto.UserInfo;
import com.vogue.supplymall.order.domain.biz.OrderUpdateBiz;
import com.vogue.supplymall.order.domain.dao.AccountPrepayDao;
import com.vogue.supplymall.order.domain.model.AccountPrepay;
import com.vogue.supplymall.order.domain.model.Order;
import com.vogue.supplymall.order.domain.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.vogue.ssm.database.dao.BaseDao;
import com.vogue.ssm.database.util.DealStatus;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.match.domain.dto.OrderPushDTO;
import com.vogue.supplymall.match.domain.service.ColValidateService;
import com.vogue.supplymall.order.domain.dao.OrderPullDao;
import com.vogue.supplymall.order.domain.model.OrderPull;
import com.vogue.supplymall.order.domain.service.OrderPullService;

@Service("orderPullService")
public class OrderPullServiceImpl extends BaseServiceImpl<OrderPull, Long> implements OrderPullService {
	private static final String commonError = "3100";
	@Resource
    private OrderPullDao orderPullDao;
	@Resource
    private MessageSourceUtils msu;
    @Resource
    private ColValidateService colValidateService;
	@Resource
	private AccountPrepayDao accountPrepayDao;
	@Resource
	private OrderUpdateBiz orderUpdateBiz;
	@Resource
	private OrderService orderService;

    /**
     * Instantiates a new Order service.
     *
     * @param baseDao the base dao
     */
    public OrderPullServiceImpl(BaseDao<OrderPull, Long> baseDao) {
        super(baseDao);
        orderPullDao = (OrderPullDao) baseDao;
    }
	@Override
	public List<Map<String, Object>> pullSell(Long syscodeid, Date maxdate) {
		return orderPullDao.pullSell(syscodeid, maxdate);
	}

	@Override
	public List<Map<String, Object>> pullBuy(Long syscodeid, Date maxdate) {
		return orderPullDao.pullBuy(syscodeid, maxdate);
	}

	@Override
	@Transactional
	public void updatePullSellState(Long syscodeid, Date maxDate, Integer pullCnt) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		String sql = "update order_status os, `order` o, order_seller ose "
//				+ " set os.pullstate = 1, os.modifydate = now() "
//				+ " where os.orderid = o.id and os.orderid = ose.orderid"
//				+ " and os.iscancel = 0 and os.orderstatus = 2 and os.pullstate <> 1"
//				+ " and ose.syscodeid = " + syscodeid 
//				+ " and o.createdate <= '" + formatter.format(maxDate) + "'";
		String sql = "update order_status os "
				+ " set os.pullstate = 1, os.modifydate = now() "
				+ " where os.orderid in (select id from ("
				+ " select o.id "
				+ "from order_status os"
				+ " join `order` o on os.orderid = o.id "
				+ " join order_seller ose on os.orderid = ose.orderid"
				+ " left join order_cancel oc on o.id=oc.orderid and oc.cancelstate in (1,2)"
				+ " where os.iscancel = 0 and os.orderstatus = 2 and os.pullstate <> 1"
				+ " and ose.syscodeid = " + syscodeid
				+ " and o.createdate <= '" + formatter.format(maxDate) + "'"
				+ " and oc.id is null"
				//+ " and oc.orderid=os.orderid and oc.cancelstate in (0,3)"
				+ " order by o.ordernumber limit " + pullCnt + ") x)";
		DealStatus.kacha();
		orderPullDao.update(sql);
	}

	@Override
	public void updatePullBuyState(Long syscodeid, Date maxDate, Integer pullCnt) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		String sql = "update order_status os, `order` o, order_buyer ob "
//				+ " set os.buypullstate = 1, os.modifydate = now() "
//				+ " where os.orderid = o.id and os.orderid = ob.orderid"
//				+ " and os.iscancel = 0 and os.orderstatus = 3 and os.buypullstate <> 1"
//				+ " and ob.syscodeid = " + syscodeid 
//				+ " and o.createdate <= '" + formatter.format(maxDate) + "'";
		String sql = "update order_status os "
				+ " set os.buypullstate = 1, os.modifydate = now() "
				+ " where os.orderid in (select id from ("
				+ " select o.id "
				+ " from order_status os"
				+ " join `order` o on os.orderid = o.id"
				+ " join order_buyer ob on os.orderid = ob.orderid"
				+ " left join order_cancel oc on o.id=oc.orderid and oc.cancelstate in (1,2)"
				+ " where buyertype=1"
				+ " and os.iscancel = 0 and os.orderstatus = 3 and os.buypullstate <> 1"
				+ " and ob.syscodeid = " + syscodeid
				+ " and o.createdate <= '" + formatter.format(maxDate) + "'"
				+ " and oc.id is null"
				//+ " and oc.orderid=os.orderid and oc.cancelstate in (0,3)"
				+ " order by o.ordernumber limit " + pullCnt + ") x)";
		DealStatus.kacha();
		orderPullDao.update(sql);
	}

	@Override
	public Map<String, Object> reducePullSellState(Long syscodeid, List<OrderPushDTO> opDTOs) {
		Map<String, Object> resultMap = new HashMap<>();

		List<String> delIdsList = new ArrayList<>();		//更新删除订单用
		List<String> auditIdsList = new ArrayList<>();	//更新审核订单用
		List<String> repeatList = new ArrayList<>();		//存储重复订单用
		List<String> allList = new ArrayList<>();		//存储全部订单id用
		List<Map<String, Object>> errList = new ArrayList<>();
		boolean resultFlag = true;
		int delCnt = 0;
		int auditCnt = 0;
		int successCnt = 0;
		int failCnt = 0;
		//0：卖家 1：买家
		int pullType = 0;
		//将订单号拆分放入集合中,并将相同操作类型的订单号集中在一起
		for (OrderPushDTO opDTO:opDTOs) {
			int type = opDTO.getType();
			String ids = opDTO.getOrderNums();
			pullType = opDTO.getPullType();
			if (type == 0) {		//删除的订单
				String[] delArr = ids.split(",");
				for (int i = 0; i < delArr.length; i++) {
					String id = delArr[i];
					delIdsList.add(id);
					allList.add(id);
				}
			} else if (type == 1) {	//审核外销出库单的订单
				String[] auditArr = ids.split(",");
				for (int i = 0; i < auditArr.length; i++) {
					String id = auditArr[i];
					auditIdsList.add(id);
					allList.add(id);
				}
			}
		}

		if (allList.size() > 0) {
			//判断删除的订单和审核的订单号是否有重复
			if (delIdsList.size() > 0 && auditIdsList.size() > 0) {
				for (String id:delIdsList) {
					if (auditIdsList.contains(id)) {
						List<String> infoList = new ArrayList<>();
						repeatList.add(id);
						//存储订单重复信息
						infoList.add(msu.getMessage("2801", new String[] {id}));
						this.addValueToErrlist(errList, "", id, infoList);
						resultFlag = false;
					}
				}
			}
			//如果订单信息重复，不往下进行
			if (resultFlag) {
				if (delIdsList.size() > 0) {
					//更新对接系统删除的订单的状态为待发货,拉取状态为撤销
					Map<String, Object> delParamMap = new HashMap<>();
					delParamMap.put("syscodeId", syscodeid);
					delParamMap.put("orderNums", delIdsList);
					if (pullType == 0) {
						delParamMap.put("pullstate", 2);
						delParamMap.put("status", 2);
						delCnt = this.update0(orderPullDao.updateOrderBillStatus(), delParamMap);
					} else {
						delParamMap.put("buypullstate", 2);
						delParamMap.put("status", 3);
						delCnt = this.update0(orderPullDao.updateBuyOrderBillStatus(), delParamMap);
					}

					//处理未更新成功的单据
					if (delIdsList.size() > delCnt) {
						String sql = orderPullDao.findUpdateFailBill();
						List<Map<String, Object>> failList = this.query0(sql, delParamMap);
						if (failList.size() > 0) {
							this.dealErrorInfo(failList, errList);
							resultFlag = false;
						} else {
							delCnt = delIdsList.size();
						}
					}
				}

				if (auditIdsList.size() > 0) {
					//更新对接系统审核的订单的状态为待收货
					Map<String, Object> auditParamMap = new HashMap<>();
					auditParamMap.put("syscodeId", syscodeid);
					auditParamMap.put("orderNums", auditIdsList);
					if (pullType == 0) {
						auditParamMap.put("status", 3);
						auditParamMap.put("pullstate", 1);
						auditCnt = this.update0(orderPullDao.updateOrderBillStatus(), auditParamMap);
					} else {
						auditParamMap.put("status", 4);
						auditParamMap.put("buypullstate", 1);
						auditCnt = this.update0(orderPullDao.updateBuyOrderBillStatus(), auditParamMap);
						for (String orderNum : auditIdsList) {
							UserInfo userInfo = new UserInfo();
							Order order = orderService.getOrder(orderNum,syscodeid);
							if (null != order) {
								String sql = "SELECT a.id accountId,s.entname,s.id sellerId "
										+ "from order_seller s,order_buyer b ,account a "
										+ "where s.orderid = b.orderid "
										+ "and a.syscodeid = b.syscodeid "
										+ "and a.organid = b.organid "
										+ "and a.matchid = b.matchid "
										+ "and s.orderid = " + order.getId() ;
								List<Map<String, Object>> list = orderPullDao.query(sql);
								if(null != list && null != list.get(0)) {
									Map<String, Object> map = list.get(0);
									userInfo.setSyscodeid(order.getSyscodeid());
									userInfo.setAccountid(Long.valueOf(map.get("accountId").toString()));//平台账户id
									userInfo.setEntName(map.get("entname").toString());//企业名称
									userInfo.setLoginId(Long.valueOf(map.get("sellerId").toString()));//登录id

									orderUpdateBiz.orderReceiving(order, null, userInfo);
								}
							}
						}
					}
					//处理未更新成功的单据
					if (auditIdsList.size() > auditCnt) {
						String sql = orderPullDao.findUpdateFailBill();
						List<Map<String, Object>> failList = this.query0(sql, auditParamMap);
						if (failList.size() > 0) {
							this.dealErrorInfo(failList, errList);
							resultFlag = false;
						} else {
							auditCnt = auditIdsList.size();
						}
					}
				}
			}
		}
		//整理结果
		successCnt = delCnt + auditCnt;
		failCnt = allList.size() - successCnt;
		resultMap.put("result", resultFlag);
		resultMap.put("details", errList);
		resultMap.put("successCnt", successCnt);
		resultMap.put("failCnt", failCnt);
		return resultMap;
	}

	/**
	 * 整理错误信息
	 */
	public List<Map<String, Object>> dealErrorInfo(List<Map<String, Object>> failList, List<Map<String, Object>> errList) {
		for (Map<String, Object> map:failList) {
			List<String> infoList = new ArrayList<>();
			String ordernumber = (String) map.get("ordernumber");
			boolean iscancel = (boolean) map.get("iscancel");
			Long status = (Long) map.get("orderstatus");
			int orderstatus = status.intValue();
			if (iscancel) {
				infoList.add(msu.getMessage("2804", null));
				this.addValueToErrlist(errList, "", ordernumber, infoList);
				continue;
			}
			if (orderstatus == 4) {
				infoList.add(msu.getMessage("2805", null));
				this.addValueToErrlist(errList, "", ordernumber, infoList);
			}
		}
		return errList;
	}
	/**
	 * 装配错误信息
	 */
	public List<Map<String, Object>> addValueToErrlist(List<Map<String, Object>> errList, String name, String id, List<String> infoList) {
		Map<String, Object> repeatMap = new HashMap<>();
		repeatMap = colValidateService.setValueForErrMap(name, id, infoList, commonError);
		errList.add(repeatMap);
		return errList;
	}

	@Override
	public List<Map<String, Object>> findOrderNumsByOrderNums(List<String> onList) {
//		Map<String, Object> paramMap=new HashMap<>();
//		paramMap.put("orderNums", onList);
//		DealStatus.kacha();
//		String sql=orderPullDao.findOrderNumsByOrderNums();
		StringBuilder nums = new StringBuilder();
		for (String num : onList) {
			nums.append(num)
				.append(",");
		}
		String orderNumbers = nums.toString();
		if (StringUtils.isNotBlank(orderNumbers)) {
			orderNumbers = orderNumbers.substring(0, orderNumbers.length() - 1);
		}
		String sql = "select o.ordernumber"
				+ " from `order` o"
				+ " where o.ordernumber in (" + orderNumbers + ")";
		List<Map<String, Object>> orderNumList = this.query(sql);
		return orderNumList;
	}

	@Override
	public Map<String, Object> pullSellCount(Long syscodeid, Date maxdate) {
		return orderPullDao.pullSellCount(syscodeid, maxdate);
	}

	@Override
	public Map<String, Object> pullBuyCount(Long syscodeid, Date maxdate) {
		return orderPullDao.pullBuyCount(syscodeid, maxdate);
	}

	@Override
	public List<Map<String, Object>> getPayModeByOrderId(String orderIds) {
		return orderPullDao.getPayModeByOrderId(orderIds);
	}

	@Override
	public Map<String, Object> pullRefundSellCount(Long syscodeid, Date maxdate) {
		return orderPullDao.pullRefundSellCount(syscodeid, maxdate);
	}

	@Override
	public List<Map<String, Object>> pullRefundSell(Long syscodeid, Date maxdate) {
        List<Map<String, Object>> list = orderPullDao.pullRefundSell(syscodeid, maxdate);
		return list;
	}

	@Override
	public List<Map<String, Object>> getPayModeByRefundOrderId(String orderIds) {
		return orderPullDao.getPayModeByRefundOrderId(orderIds);
	}

	@Override
	@Transactional
	public void updatePullRefundSellState(Long syscodeid, Date maxDate, Integer pullCnt) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String sql = "UPDATE refund_status os " +
				"SET os.sellerpullstate = 1,os.refundstatus = 4, " +
				"os.modifydate = now( ) " +
				"WHERE " +
				"os.refundid IN (" +
								"SELECT id FROM " +
								"(" +
									"SELECT r.id " +
									"FROM " +
										"refund_order r, " +
										"refund_status os, " +
										"order_seller ose," +
										"`order` o," +
										"order_status s " +
									"WHERE " +
										"os.refundid = r.id " +
										"AND r.autoflag = 0 " + //自动退货单不需要拉取
										"AND r.orderid = ose.orderid " +
										"AND os.sellerpullstate <> 1 " +
										"AND os.refundstatus = 0 " +
										"and r.orderid = o.id " +
										"and s.orderid = o.id "
                                        + "and s.orderstatus = 4 "
										+ "and s.iscancel =0 and s.pullstate = 1 " +
										"AND ose.syscodeid =  " + syscodeid +
										" AND r.createdate <= '" + formatter.format(maxDate) + "' " +
									"ORDER BY r.refundnumber " +
									"LIMIT " + pullCnt + " " +
								") x " +
								")";

		DealStatus.kacha();
		orderPullDao.update(sql);
	}

	//0 删除 1 审核 2 同意 3 拒绝
	@Override
	@Transactional
	public Map<String, Object> reducePullSellRefundState(Long syscodeid, List<OrderPushDTO> opDTOs) {
		Map<String, Object> resultMap = new HashMap<>();

		List<String> delIdsList = new ArrayList<>();		//更新删除订单用
		List<String> auditIdsList = new ArrayList<>();	//更新审核订单用
		List<String> agreeIdsList = new ArrayList<>();	//更新审核订单用
		List<String> disagreeIdsList = new ArrayList<>();	//更新审核订单用

		List<String> repeatList = new ArrayList<>();		//存储重复订单用
		List<String> allList = new ArrayList<>();		//存储全部订单id用
		List<Map<String, Object>> errList = new ArrayList<>();
		boolean resultFlag = true;
		int delCnt = 0;
		int auditCnt = 0;
		int agreeCnt = 0; //同意总数量
		int disagreeCnt = 0; //拒绝总数量
		int successCnt = 0;
		int failCnt = 0;
		//0：卖家 1：买家
		int pullType = 0;

		//将订单号拆分放入集合中,并将相同操作类型的订单号集中在一起
		for (OrderPushDTO opDTO:opDTOs) {
			int type = opDTO.getType();
			String ids = opDTO.getOrderNums();
			pullType = opDTO.getPullType();

			String[] arr = ids.split(",");
			if (type == 0) { //删除的订单
				for (int i = 0; i < arr.length; i++) {
					String id = arr[i];
					delIdsList.add(id);
					allList.add(id);
				}
			} else if (type == 1) { //审核外销退货单的订单
				for (int i = 0; i < arr.length; i++) {
					String id = arr[i];
					auditIdsList.add(id);
					allList.add(id);
				}
			} else if (type == 2) { // 同意
				for (int i = 0; i < arr.length; i++) {
					String id = arr[i];
					agreeIdsList.add(id);
					allList.add(id);
				}
			} else if (type == 3) { // 拒绝
				for (int i = 0; i < arr.length; i++) {
					String id = arr[i];
					disagreeIdsList.add(id);
					allList.add(id);
				}
			}
		}

		if (allList.size() > 0) {

			//判断删除的订单和审核的订单号是否有重复
			if (delIdsList.size() > 0 && auditIdsList.size() > 0) {

				for (String id:delIdsList) {
					if (auditIdsList.contains(id)) {
						List<String> infoList = new ArrayList<>();
						repeatList.add(id);

						//存储订单重复信息
						infoList.add(msu.getMessage("2801", new String[] {id}));
						this.addValueToErrlist(errList, "", id, infoList);
						resultFlag = false;
					}
				}
			}

			//如果订单信息重复，不往下进行
			if (resultFlag) {
				if (delIdsList.size() > 0) {
					//更新对接系统删除的订单的状态为待发货,拉取状态为撤销
					Map<String, Object> map = new HashMap<>();
					map.put("syscodeId", syscodeid);
					map.put("orderNums", delIdsList);

					if (pullType == 0) {
						map.put("status", 0);
						map.put("pullstate", 2);
						delCnt = this.update0(orderPullDao.updateRefundBillStatus(), map);
					}
					/*else {
						delParamMap.put("buypullstate", 2);
						delParamMap.put("status", 3);
						delCnt=this.update0(orderPullDao.updateBuyOrderBillStatus(), delParamMap);
					}*/

					//处理未更新成功的单据
					if (delIdsList.size() > delCnt) {
						String sql = orderPullDao.findUpdateFailRefundBill();
						List<Map<String, Object>> failList = this.query0(sql, map);

						if (failList.size() > 0) {
							this.dealErrorInfo(failList, errList);
							resultFlag = false;
						} else {
							delCnt = delIdsList.size();
						}
					}
				}


				//同意
				if (agreeIdsList.size() > 0) {
					//更新对接系统审核的订单的状态为同意
					Map<String, Object> map = new HashMap<>();
					map.put("syscodeId", syscodeid);
					map.put("orderNums", agreeIdsList);

					if (pullType == 0) {
						map.put("status", 1);
						map.put("pullstate", 1);
						agreeCnt = this.update0(orderPullDao.updateRefundBillStatus(), map);
					}
					/*else {
						auditParamMap.put("status", 4);
						auditParamMap.put("buypullstate", 1);
						agreeCnt=this.update0(orderPullDao.updateBuyOrderBillStatus(), auditParamMap);
					}*/

					//处理未更新成功的单据
					if (agreeIdsList.size() > agreeCnt) {
						String sql = orderPullDao.findUpdateFailRefundBill();
						List<Map<String, Object>> failList = this.query0(sql, map);
						if (failList.size() > 0) {
							this.dealErrorInfo(failList, errList);
							resultFlag = false;
						} else {
							agreeCnt = agreeIdsList.size();
						}
					}

				}
				//拒绝
				if (disagreeIdsList.size() > 0) {
					//更新对接系统审核的订单的状态为拒绝
					Map<String, Object> map = new HashMap<>();
					map.put("syscodeId", syscodeid);
					map.put("orderNums", disagreeIdsList);

					if (pullType == 0) {
						map.put("status", 2);
						map.put("pullstate", 1);
						disagreeCnt = this.update0(orderPullDao.updateRefundBillStatus(), map);
					}
					/*else {
						auditParamMap.put("status", 4);
						auditParamMap.put("buypullstate", 1);
						disagreeCnt=this.update0(orderPullDao.updateBuyOrderBillStatus(), auditParamMap);
					}*/

					//处理未更新成功的单据
					if (disagreeIdsList.size() > disagreeCnt) {
						String sql = orderPullDao.findUpdateFailRefundBill();
						List<Map<String, Object>> failList = this.query0(sql, map);
						if (failList.size() > 0) {
							this.dealErrorInfo(failList, errList);
							resultFlag = false;
						} else {
							disagreeCnt = disagreeIdsList.size();
						}
					}
				}
				//审核
				if (auditIdsList.size() > 0) {
					/**
					 * 1.更新单据状态 refund_status
					 * 2.退货单支付 refund_payment
					 * 3.账户明细和主表 account_prepay_detail、account_prepay
					 */
					Map<String, Object> map = new HashMap<>();
					map.put("syscodeId", syscodeid);
					map.put("orderNums", auditIdsList);
					if (pullType == 0) {
						String orderNums = "";
						for (String s : auditIdsList){
							orderNums += " '" + s + "',";
						}
						orderNums = orderNums.substring(0, orderNums.length() - 1);
						map.put("status", 3);
						map.put("pullstate", 1);
						//更新对接系统审核的订单的状态为完成
						//auditCnt = this.update0(orderPullDao.updateRefundBillStatus(), map);
						/*String selectRefundSql = " select o.id from refund_status os, refund_order o, order_seller ose "
								+ " where os.refundid = o.id and o.orderid = ose.orderid "
								+ " and os.sellerpullstate = 1 "
								+ " and ose.syscodeid = " + syscodeid
								+ " and o.refundnumber in (" + orderNums + ")"
								+ " and os.refundstatus<>3 ;";
						List<Map<String, Object>> selectRefundList = orderPullDao.query(selectRefundSql);
						auditCnt = selectRefundList.size();*/

						String updateRefundSql = " update refund_status os, refund_order o, order_seller ose "
								+ " set os.refundstatus = 3, os.modifydate = now(),os.sellerpullstate=1 "
								+ " where os.refundid = o.id and o.orderid = ose.orderid "
								+ " and os.sellerpullstate = 1 "
								+ " and ose.syscodeid = " + syscodeid
								+ " and o.refundnumber in (" + orderNums + ")"
								+ " and os.refundstatus<>3 ; ";
						auditCnt = orderPullDao.update(updateRefundSql);
						////////////////选择预付货款的退货单要退钱/////////


						String sql = "SELECT DISTINCT ro.tendid,ro.id refundid,a.id accountid,"
										+ "ose.syscodeid sellsyscodeid,ose.organid sellorganid,ose.matchid  sellmatchid,"
										+ "obu.syscodeid buysyscodeid,obu.organid buyorganid,obu.matchid  buymatchid,"
										+ "ro.finalprice "
									+ "FROM "
									+ "refund_order ro ,order_seller ose ,order_buyer obu,account a "
									+ "WHERE "
									+ " ro.orderid = ose.orderid and ro.orderid = obu.orderid AND ro.refundway = 4 "
									+ "AND ro.refundnumber IN (" + orderNums + ") "
									+ "and a.tendid = ro.tendid and  a.syscodeid = ro.syscodeid "
									+ "and a.organid = obu.organid and a.matchid = obu.matchid ";
						List<Map<String, Object>> list = orderPullDao.query(sql);

						if (list != null && list.size() > 0) {
							BigDecimal balance = new BigDecimal(0);
							StringBuilder paymentSql = new StringBuilder();
							StringBuilder prepayDetailSql = new StringBuilder();
							StringBuilder prepaySql = new StringBuilder();
							AccountPrepay ap = new AccountPrepay();
							prepayDetailSql.append("INSERT INTO `account_prepay_detail` (`id`, `tendid`, `refundid`, `accountid`, ")
									.append("`sellsyscodeid`, `sellorganid`, `sellmatchid`, `buysyscodeid`, `buyorganid`, `buymatchid`, ")
									.append("`createdate`, `modifydate`, `amount`, `type`, `origin`, `memo`) VALUES ");
							for (Map<String, Object> m : list) {
								prepayDetailSql.append("(").append(SnowflakeIdWorker.getIns().nextId()).append(",")
										.append(m.get("tendid")).append(",")
										.append(m.get("refundid")).append(",")
										.append(m.get("accountid")).append(",")
										.append(m.get("sellsyscodeid")).append(",")
										.append(m.get("sellorganid")).append(",")
										.append("'").append(m.get("sellmatchid")).append("'").append(",")
										.append(m.get("buysyscodeid")).append(",")
										.append(m.get("buyorganid")).append(",")
										.append("'").append(m.get("buymatchid")).append("'").append(",")
										.append("now()").append(",")
										.append("now()").append(",")
										.append(m.get("finalprice")).append(",")
										.append(4).append(",")
										.append(2).append(",")
										.append("''").append(")").append(",");

								paymentSql.append(" update refund_payment set paymentdate = now(),modifydate =now(),archivestatus = 1")
										.append(" where refundid = ")
										.append(m.get("refundid"))
										.append(";");

								ap = accountPrepayDao.selectOneByWhr("buysyscodeid=" + m.get("buysyscodeid")
										+ " and buyorganid=" + m.get("buyorganid")
										+ " and sellorganid=" + m.get("sellorganid")+" ");
								balance = ap.getBalance();
								balance = balance.add(new BigDecimal(m.get("finalprice").toString()));

								prepaySql.append(" update account_prepay set balance= "+balance+" where id="+ap.getId()+" and balance="+ap.getBalance()+ ";");
							}

							String s = prepayDetailSql.substring(0, prepayDetailSql.length() - 1) + ";";

							DealStatus.kacha();
							orderPullDao.update(s);
							orderPullDao.update(paymentSql.toString());
							orderPullDao.update(prepaySql.toString());

						}
						//////////////选择预付货款的退货单要退钱！///////////
					}
					/*else {
						auditParamMap.put("status", 4);
						auditParamMap.put("buypullstate", 1);
						auditCnt=this.update0(orderPullDao.updateBuyOrderBillStatus(), auditParamMap);
					}*/

					//处理未更新成功的单据
					if (auditIdsList.size() > auditCnt) {
						String sql = orderPullDao.findUpdateFailRefundBill();
						List<Map<String, Object>> failList = this.query0(sql, map);

						if (failList.size() > 0) {
							this.dealErrorInfo(failList, errList);
							resultFlag = false;
						} else {
							auditCnt = auditIdsList.size();
						}
					}

				}
			}
		}

		//整理结果
		successCnt = delCnt + auditCnt + agreeCnt + disagreeCnt;
		failCnt = allList.size() - successCnt;
		resultMap.put("result", resultFlag);
		resultMap.put("details", errList);
		resultMap.put("successCnt", successCnt);
		resultMap.put("failCnt", failCnt);

		return resultMap;
	}
}
